import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import {
  DriverSelect,
  GroupTreeSelect,
  LineSelect,
  VehicleSelect,
} from '@/components/CustomForm';
import { PLATE_COLOR_MAP, TRIP_STATE_MAP } from '@/constants/enums';
import useMaterial from '@/hooks/useMaterial';
import { formatSeconds } from '@/utils/format';
import request from '@/utils/request';
import { DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
import { Button, message, Modal, Space } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import Save from '../trip-manage/components/Save';

const getList = async (params) => {
  const res = await request({
    url: '/datas/trip/abnormal/list',
    method: 'GET',
    custom: true,
    params: params,
  });
  return {
    total: res?.total,
    data: res?.data,
  };
};

const Index = () => {
  const [mode, setMode] = useState('list');
  const [record, setRecord] = useState();
  const [selectedKeys, setSelectedKeys] = useState([]);
  const crudRef = useRef();
  const { materialTypeMap } = useMaterial();

  const deleteRow = (id) => {
    const ids = id ? [id] : selectedKeys;
    Modal.confirm({
      title: `确认删除所选数据?`,
      onOk: async () => {
        await request({
          url: '/datas/trip/delete',
          method: 'POST',
          data: { ids },
        });
        message.success('操作成功');
        crudRef.current?.reload();
        setSelectedKeys([]);
      },
    });
  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '组织',
      dataIndex: 'groupName',
      width: 220,
      fixed: 'left',
    },
    {
      title: '线路',
      dataIndex: 'lineName',
      width: 280,
      fixed: 'left',
    },
    {
      title: '车牌号',
      dataIndex: 'license',
      width: 120,
      fixed: 'left',
    },
    {
      title: '车牌颜色',
      dataIndex: 'plateColor',
      width: 90,
      render: (text) => PLATE_COLOR_MAP[text] || text,
    },
    {
      title: '驾驶员',
      dataIndex: 'realname',
      width: 100,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: '装车司机',
      dataIndex: 'loadDriver',
      width: 100,
    },
    {
      title: '装车司机电话',
      dataIndex: 'loadPhone',
      width: 120,
    },
    {
      title: '卸车司机',
      dataIndex: 'unloadDriver',
      width: 100,
    },
    {
      title: '卸车司机电话',
      dataIndex: 'unloadPhone',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 110,
      render: (text) => TRIP_STATE_MAP[text] || text,
    },
    {
      title: '是否有效',
      dataIndex: 'isValid',
      width: 100,
      render: (text) => (text === 1 ? '是' : '否'),
    },
    {
      title: '装货地',
      dataIndex: 'loadPlaceName',
      width: 150,
    },
    {
      title: '卸货地',
      dataIndex: 'unloadPlaceName',
      width: 150,
    },
    {
      title: '物料类型',
      dataIndex: 'type',
      width: 100,
      render: (text) => materialTypeMap[text] || text,
    },
    {
      title: '生成类型',
      dataIndex: 'createType',
      width: 100,
    },
    {
      title: '派单时间',
      dataIndex: 'planDate',
      width: 180,
    },
    {
      title: '趟次时间',
      dataIndex: 'tripTime',
      width: 180,
    },
    {
      title: '开始时间',
      dataIndex: 'beginTime',
      width: 180,
    },
    {
      title: '进装车地时间',
      dataIndex: 'inLoadTime',
      width: 180,
    },
    {
      title: '出装车地时间',
      dataIndex: 'outLoadTime',
      width: 180,
    },
    {
      title: '装车时长',
      dataIndex: 'loadDurations',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '进卸货地时间',
      dataIndex: 'inUnloadTime',
      width: 180,
    },
    {
      title: '出卸货地时间',
      dataIndex: 'outUnloadTime',
      width: 180,
    },
    {
      title: '卸车时长',
      dataIndex: 'unloadDurations',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      width: 180,
    },
    {
      title: '总时长',
      dataIndex: 'duration',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '空载时长',
      dataIndex: 'emptyDurations',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '重载时长',
      dataIndex: 'heavyDurations',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '停车时长',
      dataIndex: 'stopTimes',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '进站时长',
      dataIndex: 'chargeTimes',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '标准时长',
      dataIndex: 'standardTimes',
      width: 100,
      render: (text) => formatSeconds(text),
    },
    {
      title: '运营时差',
      dataIndex: 'duration',
      width: 100,
      render: (text, record) => {
        return formatSeconds(text - record.standardTimes);
      },
    },
    {
      title: '空载里程(km)',
      dataIndex: 'emptyMileages',
      width: 110,
    },
    {
      title: '重载里程(km)',
      dataIndex: 'heavyMileages',
      width: 110,
    },
    {
      title: '总里程(km)',
      dataIndex: 'mileages',
      width: 110,
    },
    {
      title: '标准里程(km)',
      dataIndex: 'standardMileages',
      width: 110,
    },
    {
      title: '平均运速(km/h)',
      dataIndex: 'avgSpeed',
      width: 140,
    },
    {
      title: '原因',
      dataIndex: 'reason',
      width: 150,
    },
    {
      title: '系统时间',
      dataIndex: 'time',
      width: 180,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 150,
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'operate',
      width: 150,
      render: (text, record) => {
        return (
          <Space>
            <a
              className="btn-operate"
              onClick={() => {
                setRecord(record);
                setMode('edit');
              }}
            >
              编辑
            </a>
            <a
              onClick={() => {
                deleteRow(record.tripId);
              }}
            >
              删除
            </a>
          </Space>
        );
      },
    },
  ];

  const fields = [
    {
      label: '组织',
      name: 'groupId',
      children: <GroupTreeSelect placeholder="请选择组织" />,
    },
    {
      label: '线路',
      name: 'lineId',
      children: <LineSelect placeholder="请选择线路" />,
    },
    {
      label: '车牌号',
      name: 'vehicleId',
      children: <VehicleSelect placeholder="请选择车牌号" />,
    },
    {
      label: '驾驶员',
      name: 'driverId',
      children: <DriverSelect placeholder="请选择驾驶员" />,
    },
    {
      label: '开始时间',
      name: 'fromTime',
      children: (
        <DatePicker
          allowClear={false}
          showTime
          placeholder="请选择开始时间"
          format="YYYY-MM-DD HH:mm:ss"
        />
      ),
    },
    {
      label: '结束时间',
      name: 'toTime',
      children: (
        <DatePicker
          allowClear={false}
          showTime
          placeholder="请选择结束时间"
          format="YYYY-MM-DD HH:mm:ss"
        />
      ),
    },
  ];

  const handleExport = async () => {
    const params = crudRef.current?.getParams();
    const res = await request({
      url: '/datas/trip/abnormal/export/list',
      method: 'GET',
      params,
    });
    window.open(res);
  };

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="tripId"
        queryFormProps={{
          labelCol: 7,
          fieldWidth: 280,
          initialValues: {
            fromTime: dayjs().startOf('day'),
            toTime: dayjs().endOf('day'),
          },
        }}
        fields={fields}
        columns={columns}
        request={getList}
        transformParams={(params) => {
          return {
            ...params,
            fromTime: params?.fromTime?.format('YYYY-MM-DD HH:mm:ss'),
            toTime: params?.toTime?.format('YYYY-MM-DD HH:mm:ss'),
          };
        }}
        toolbar={
          <>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedKeys.length === 0}
              onClick={() => deleteRow()}
            >
              批量删除
            </Button>
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              onClick={handleExport}
            >
              导出
            </Button>
          </>
        }
        tableProps={{
          rowSelection: {
            selectedRowKeys: selectedKeys,
            onChange: (selectedRowKeys) => {
              setSelectedKeys(selectedRowKeys);
            },
          },
        }}
      />
      <Save
        open={mode === 'create' || mode === 'edit'}
        record={record}
        onCancel={() => {
          setRecord();
          setMode('list');
        }}
        onOk={() => {
          setRecord();
          setMode('list');
          crudRef.current?.reload();
        }}
      />
    </>
  );
};

export default Index;
